import { Color } from "cc";

// // HSB转RGB
const hsb2rgb = function (h: number, s: number, v: number) {
    h = h % 1;
    let i = Math.floor(h * 6);
    let f = h * 6 - i;
    let p = v * (1 - s);
    let q = v * (1 - f * s);
    let t = v * (1 - (1 - f) * s);
    let r = 0, g = 0, b = 0;
    switch (i % 6) {
        case 0: r = v; g = t; b = p; break;
        case 1: r = q; g = v; b = p; break;
        case 2: r = p; g = v; b = t; break;
        case 3: r = p; g = q; b = v; break;
        case 4: r = t; g = p; b = v; break;
        case 5: r = v; g = p; b = q; break;
    }

    return new Color(Math.floor(r * 255), Math.floor(g * 255), Math.floor(b * 255), 255);
}


const rgb2hsb = function (r: number, g: number, b: number) {
    // 将RGB值标准化到0-1范围
    r = r / 255.0;
    g = g / 255.0;
    b = b / 255.0;

    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    const delta = max - min;

    let h = 0;
    let s = 0;
    let v = max;

    // 计算饱和度
    if (max !== 0) {
        s = delta / max;
    }

    // 计算色相
    if (delta !== 0) {
        if (max === r) {
            h = ((g - b) / delta) % 6;
        } else if (max === g) {
            h = (b - r) / delta + 2;
        } else {
            h = (r - g) / delta + 4;
        }

        // 确保色相在0-1范围内
        h = h / 6;
        if (h < 0) h += 1;
    }

    return { h, s, v };
}

/**
 * 添加随机颜色
 * @param colors 颜色数组
 * @param h 色相
 * @param s 饱和度
 * @param b 亮度
 * @param count 数量
 */
const addColor = function(colors:Color[], h: number, s: number, b: number, count: number){
    let color = hsb2rgb(h, s, b);
    for (let i = 0; i < count; i++) {
        colors.push(color);
    }
}


/**
 * 构建随机颜色
 * @param colorMaps 主颜色
 * @param randColors 随机颜色
 */
export const buildColors = function(colorMaps:Color[],randColors:Color[][]){

    randColors.length = 0;
    let max = colorMaps.length;

    for (let i = 0; i < max; i++) {
        
        let c = colorMaps[i];
        let hsb = rgb2hsb(c.r, c.g, c.b);

        let colors = randColors[i] = []; //重置随机颜色数组
        addColor(colors, hsb.h, hsb.s, hsb.v, 60);
        addColor(colors, hsb.h, hsb.s, hsb.v * 0.95, 20);
        addColor(colors, hsb.h, hsb.s, hsb.v * 0.85, 10);
        addColor(colors, hsb.h, hsb.s, hsb.v * 0.80, 10);
        // addColor(i, hsb.h, hsb.s, hsb.v * 1.05, 5);
    }
}